package com.lsu.app.controller.Student;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lsu.app.bean.*;
import com.lsu.app.config.target.RequestRoles;
import com.lsu.app.service.*;
import com.lsu.app.tool.R;
import com.lsu.app.tool.jiebaUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author hjj
 * @date 2023/10/16 18:56
 */
@RestController
@Slf4j
@CrossOrigin
@RequestMapping("/stLs")
public class StLessonController {
    @Autowired
    private HttpServletRequest request;
    private final ScheduleService scheduleService;
    private final CourseService courseService;

    private final ResourceService resourceService;
    private final CommentService commentService;
    private final KindService kindService;
    private final PraiseService praiseService;
    private final UserService userService;
    private final CourseScoreService courseScoreService;
    private final CollectService collectService;
    private final KvCodeService kvCodeService;
    private final LogService logService;
    private final StudyLogService studyLogService;
    public StLessonController(ScheduleService scheduleService, CourseService courseService, ResourceService resourceService, CommentService commentService, KindService kindService, PraiseService praiseService, UserService userService, CourseScoreService courseScoreService, CollectService collectService, KvCodeService kvCodeService, LogService logService, StudyLogService studyLogService) {
        this.scheduleService = scheduleService;
        this.courseService = courseService;
        this.resourceService = resourceService;
        this.commentService = commentService;
        this.kindService = kindService;
        this.praiseService = praiseService;
        this.userService = userService;
        this.courseScoreService = courseScoreService;
        this.collectService = collectService;
        this.kvCodeService = kvCodeService;
        this.logService = logService;
        this.studyLogService = studyLogService;
    }

    @RequestRoles({"student"})
    @PostMapping("/addCollect")
    @ApiOperation("a添加收藏/关注")
    public R<String> addCollect(
            @ApiParam("类型（1关注教师，2关注课程，3智能推荐,4课程表）")@RequestParam("type") Integer type,
            @ApiParam("关联[教师id/课程id/智能推荐sets的id]")@RequestParam("linkId") Integer linkId
    ){
        User user = userService.getById(linkId);
        if (type!=1&&type!=2&&type!=3&&type!=4){
            return R.err("类型错误");
        }
        if(collectService.collectCount(linkId,type)==1){
            return R.err("您已经收藏/关注过");
        }
        Integer teacherId = linkId;
        if(type==1){
            if(user==null||user.getState()==0){
                return R.err("教师不存在");
            }else{
                collectService.save(new Collect(teacherId,(Integer) request.getSession().getAttribute("id"),type,linkId, LocalDateTime.now().toString()));
                logService.createLog("COLLECT_CREATE","collect_teacher："+user.getName(),"user-"+request.getSession().getAttribute("username"));
            }
        }else if(type==2){
            Course course = courseService.getById(linkId);
            teacherId=courseService.getTeacherIdByCourseId(linkId);
            if(course==null){
                return R.err("课程不存在");
            }else {
                collectService.save(new Collect(teacherId,(Integer) request.getSession().getAttribute("id"),type,linkId, LocalDateTime.now().toString()));
                logService.createLog("COLLECT_CREATE","collect_course："+course.getCourseName(),"user-"+request.getSession().getAttribute("username"));
            }
        }else if(type==3){
//            CourseSets set = setsService.getById(linkId);
//            teacherId=courseService.getTeacherIdByCourseId(set.getCourseId());
//            if (set==null){
//                return R.err("课程集合不存在");
//            }else{
//                collectService.save(new Collect(teacherId,(Integer) request.getSession().getAttribute("id"),type,linkId, LocalDateTime.now().toString()));
//                logService.createLog("COLLECT_CREATE","collect_set："+set.getId(),"user-"+request.getSession().getAttribute("username"));
//            }
        } else if (type==4){
            Schedule schedule = scheduleService.getById(linkId);
            teacherId=schedule.getUserId();
            if(schedule==null){
                return R.err("课程表不存在");
            }else{
                collectService.save(new Collect(teacherId,(Integer) request.getSession().getAttribute("id"),type,linkId, LocalDateTime.now().toString()));
                logService.createLog("COLLECT_CREATE","collect_schedule："+schedule.getName(),"user-"+request.getSession().getAttribute("username"));
            }
        }
        return R.success("保存成功");
    }
    @RequestRoles({"student"})
    @DeleteMapping("/delTeaCol")
    @ApiOperation("aa删除关注[根据type和linkId]")
    public R<String> delColTL(
        @ApiParam("类型（1教师，2课程）")@RequestParam("type") Integer type,
        @ApiParam("教师id或课程id")@RequestParam("linkId") Integer linkId
    ){
        Integer userId = (Integer) request.getSession().getAttribute("id");
        collectService.remove(new LambdaQueryWrapper<Collect>().eq(Collect::getType,type).eq(Collect::getLinkId,linkId).eq(Collect::getUserId,userId));
        logService.createLog("COLLECT_DELETE","collect_delete","user-"+request.getSession().getAttribute("username"));
        return R.success("删除成功");
    }

    @RequestRoles({"student"})
    @DeleteMapping("/delCollect")
    @ApiOperation("a删除收藏/关注")
    public R<String> delCollect(
            @ApiParam("收藏/关注id")@RequestParam("id") Integer id
    ){
        if (collectService.removeById(id)){
            logService.createLog("COLLECT_DELETE","collect_delete","user-"+request.getSession().getAttribute("username"));
            return R.success("删除成功");
        }else{
            return R.err("删除失败");
        }
    }
    @RequestRoles({"student"})
    @GetMapping("/getCollects")
    @ApiOperation("a获取收藏/关注信息[分页]")
    public R<Page<Collect>> getCollects(
            @ApiParam("当前页")@RequestParam("pageCur") Integer pageCur,
            @ApiParam("页码")@RequestParam("pageSize") Integer pageSize,
            @ApiParam("类型（1关注教师，2关注课程，3智能推荐,4课程表）")@RequestParam("type") Integer type
    ){
        if(type!=1&&type!=2&&type!=3&&type!=4){
            return R.err("获取类型错误");
        }
        Integer userId = (Integer) request.getSession().getAttribute("id");
        LambdaQueryWrapper<Collect> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Collect::getUserId,userId).eq(Collect::getType,type);
        Page<Collect> page = collectService.page(new Page<>(pageCur, pageSize), wrapper);
        for (Collect record : page.getRecords()) {
            if(type==1){
                User user = userService.getById(record.getLinkId());
                if(user!=null&&user.getState()==1){
                    user.setImageUrl(resourceService.getHeadUrlByUorrIdAndType(user.getId()));
                    user.setTaste(userService.getTasteById(user.getId()));
                    user.setSelfLikeCollect(1);
                    user.setFans(collectService.CountByTeacherId(record.getTeacherId()));
                    record.setLinkClass(user);
                }else{
                    record.setLinkClass("教师不存在或已注销");
                }
            }else if(type==2){
                Course course = courseService.getById(record.getLinkId());
                if(course!=null){
                    course.setTeacherName(courseService.getTeacherNameByTeacherId(course.getTeacherId()));
                    course.setCoverImgUrl(resourceService.getCoverImgUrlByCourseId(course.getId()));
                    course.setResponds(commentService.getCountByTypeAndLinkId(1,course.getId()));
                    course.setKindName(kindService.getValueByCourseId(course.getId()));
                    course.setSelfLike(praiseService.getSelfLike(course.getId(),3));
                    record.setLinkClass(course);
                }else{
                    record.setLinkClass("课程不存在或已删除");
                }
            } else if(type==4){
                Schedule schedule = scheduleService.getById(record.getLinkId());
                if (schedule!=null){
                    schedule.setUserNicName(userService.getNameById(schedule.getUserId()));
                }else {
                    record.setLinkClass("课程表不存在或已删除");
                }
            }
//            else if(type==3){
//
//            }
        }
        return R.success(page);
    }
    @RequestRoles({"student"})
    @PostMapping("/setScore")
    @ApiOperation("d课程评分")
    public R<CourseScore> setScore(
        @ApiParam("课程id")@RequestParam("courseId") Integer courseId,
        @ApiParam("评分值(int)[0,1,2,3,4,5]")@RequestParam("score") Integer score
    ){
        if(courseService.getById(courseId)==null){
            return R.err("课程id不存在");
        }
        if(score!=0&&score!=1&&score!=2&&score!=3&&score!=4&&score!=5){
            return R.err("分数异常");
        }
        Integer stuId = (Integer) request.getSession().getAttribute("id");
        CourseScore courseScore = new CourseScore(courseId,stuId,score,LocalDateTime.now().toString());
        courseScoreService.save(courseScore);
        return R.success(courseScoreService.getById(courseScore.getId()));
    }
    @RequestRoles({"student"})
    @PostMapping("/startStudyLog")
    @ApiOperation("创建学习日志开始")
    public R<StudyLog> createStartStudyLog(
        @ApiParam("课程视频id")@RequestParam("videoId") Integer videoId
    ){
        Integer userId = (Integer) request.getSession().getAttribute("id");
        Resource video = resourceService.getById(videoId);
        StudyLog log = new StudyLog(userId,String.valueOf(System.currentTimeMillis()),video.getUorrId(),LocalDateTime.now().toString(),video.getEpisodes());
        studyLogService.save(log);
        return R.success(studyLogService.getById(log.getId()));
    }
    @RequestRoles({"student"})
    @PutMapping("/endStudyLog")
    @ApiOperation("创建学习日志结束")
    public R<StudyLog> createEndStudyLog(
            @ApiParam("学习日志id")@RequestParam("logId") Integer logId
    ){
       String startTime = studyLogService.getById(logId).getStudyTime();
            long times = System.currentTimeMillis()- Long.parseLong(startTime);
            studyLogService.update(new LambdaUpdateWrapper<StudyLog>().eq(StudyLog::getId,logId)
                    .set(StudyLog::getStudyTime,times)
                    .set(StudyLog::getEndTime,LocalDateTime.now().toString())
                    .set(StudyLog::getState,1));
        return R.success(studyLogService.getById(logId));
    }
    @RequestRoles({"student"})
    @GetMapping("/getHistory")
    @ApiOperation("获取观看历史记录(两周内)")
    public R<List<StudyLog>> getHistory(){
        Integer studentId = (Integer) request.getSession().getAttribute("id");
        List<StudyLog> list = studyLogService.getStudyLogByUserId(studentId);
        for (StudyLog studyLog : list) {
            Course course = courseService.getById(studyLog.getCourseId());
            course.setTeacherName(courseService.getTeacherNameByTeacherId(course.getTeacherId()));
            course.setCoverImgUrl(resourceService.getCoverImgUrlByCourseId(course.getId()));
            course.setResponds(commentService.getCountByTypeAndLinkId(1,course.getId()));
            course.setKindName(kindService.getValueByCourseId(course.getId()));
            course.setSelfLike(praiseService.getSelfLike(course.getId(),3));
            studyLog.setCourse(course);
            studyLog.setStudyTime(jiebaUtil.msToss(studyLog.getStudyTime()));
        }
        return R.success(list);
    }

}
